<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      v-show="showSearch"
      :inline="true"
    >
      <el-form-item label="排班人员" prop="creator">
        <el-input
          v-model="queryParams.creator"
          placeholder="请输入排班人员"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="排班班组" prop="deptId">
        <el-select
          v-model="queryParams.deptId"
          placeholder="班组"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in deptInfo"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['job:termSchedule:add']"
          >下载模板
        </el-button>

        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['job:termSchedule:add']"
          >导入
        </el-button>

        <!-- //ToDo Hush.-->
        <!--        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['job:termSchedule:export']"
        >导出
        </el-button>-->

        <el-button
          type="primary"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['job:termSchedule:del']"
          >删除
        </el-button>
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="termScheduleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column
        label="序号"
        type="index"
        align="center"
      ></el-table-column>
      <el-table-column
        label="排班班组"
        prop="deptName"
        :show-overflow-tooltip="true"
        align="center"
      />
      <el-table-column label="排班日期" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.scheduleStartTime + " - " + scope.row.scheduleEndTime
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="排班人员"
        prop="creator"
        :show-overflow-tooltip="true"
        align="center"
      />
      <el-table-column
        label="操作时间"
        prop="handleTime"
        align="center"
      ></el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="handleShowDel(scope.row.scheduleStartTime)"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['job:termSchedule:del']"
            >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['job:termSchedule:view']"
            >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--  新增排班模板 -s  -->
    <el-dialog :title="title" :visible.sync="open" width="540px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <span style="font-weight:bold">基本信息</span>
        <el-divider></el-divider>
        <el-row>
          <el-form-item label="排班班组" prop="dept">
            <el-select
              v-model="form.dept"
              value-key="deptId"
              placeholder="选择班组"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in deptInfo"
                :label="dict.deptName"
                :key="dict.deptId"
                :value="dict"
              />
            </el-select>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="排班时间" prop="scheduleDateRange">
            <!--v1.2 版本修改为月份-->
            <!-- <el-date-picker
              v-model="form.scheduleDateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker> -->
            <el-date-picker
              v-model="form.scheduleDateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM"
              type="month"
              placeholder="选择月份"
            >
            </el-date-picker>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitForm"
          title="点击即可下载该班组模板"
          >下 载</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  排班模板上传 -s  -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-change="beforeUpload"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="upload.isUploading"
          :disabled="upload.isUploading"
          >{{
            upload.isUploading ? "生成中，时间稍长，请耐心等待..." : "上 传"
          }}</el-button
        >
        <el-button @click="uploadCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 排班详情对话框 -s -->
    <el-dialog
      :title="title"
      :visible.sync="openView"
      width="990px"
      append-to-body
    >
      <el-form ref="formView" :model="formView" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名" prop="userName">
              <el-input
                v-model="detailQuery.staffName"
                placeholder="请输入员工姓名"
                clearable
                size="small"
                style="width: 180px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="idCard">
              <el-input
                v-model="detailQuery.idCard"
                placeholder="请输入身份证号"
                clearable
                size="small"
                style="width: 180px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="岗位" prop="stationName">
              <el-input
                v-model="detailQuery.stationName"
                placeholder="请输入岗位"
                clearable
                size="small"
                style="width: 180px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-button
                icon="el-icon-search"
                size="mini"
                @click="handleViewTableQuery"
                >搜索</el-button
              >

              <el-button
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImportToCover"
                title="注意:需上传原文件进行覆盖"
                >覆盖
              </el-button>

              <el-button
                icon="el-icon-refresh"
                size="mini"
                @click="resetDetailQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        :data="tableData"
        border
        v-loading="userloading"
        style="width: 100%"
        height="600px"
      >
        <el-table-column
          prop="staffName"
          label="姓名"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="idCard"
          label="身份证"
          width="250px"
        ></el-table-column>

        <el-table-column
          prop="deptName"
          label="班组名称"
          width="180px"
        ></el-table-column>

        <el-table-column
          prop="areaName"
          label="区域名称"
          width="180px"
        ></el-table-column>

        <el-table-column
          prop="stationName"
          label="岗位"
          width="180px"
        ></el-table-column>

        <el-table-column
          align="center"
          v-for="(item, index) in planDays"
          :key="index + item"
          :label="item"
          width="100px"
          :prop="item"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.planDays[index].attendanceGroupName }}</div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCurrentMonthFirstDay,
  getCurrentMonthLastDay
} from "@/utils/DateUtils";
import { getToken } from "@/utils/auth";
import {
  shiftDateVerification,
  listTermSchedule,
  importSchedule,
  getTermSchedule,
  delTermSchedule
} from "@/api/job/termSchedule/index_new";
import { tableRecords } from "@/api/system/dept";
import { timeAfterNow } from "@/utils/DateUtils";

export default {
  name: "termSchedule",
  directives: {
    focus: {
      // 指令的定义
      inserted: function(el) {
        el.getElementsByTagName("input")[0].focus();
      }
    }
  },

  data() {
    return {
      show: false,
      type: 1,
      disabledValue: true,
      fileList: [],
      uploadText: "导入",
      uploadLoading: false,
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "导入排班信息",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/scheduling/plan/importTemplate"
      },
      needNumber: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids: [],
      statusArray: [],
      flag: false,
      loading: true,
      userloading: false,
      isEdit: false,
      // 总条数
      total: 0,
      pageNum: 1,
      pageSize: 10,
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // // 是否显示弹出层
      openSchedule: false,
      // 是否显示弹出层
      openView: false,
      // 是否显示弹出层
      openCycle: false,
      // 导出遮罩层
      exportLoading: false,
      // 日期范围
      dateRange: [],
      scheduleDateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        creator: undefined,
        deptId: undefined,
        status: undefined
      },
      colorParams: {
        xx: "",
        qk: ""
      },
      rowIndex: "",
      columnIndex: "",
      tableData: [],
      //考勤天数组
      planDays: [],
      resultData: "",
      tableTitleData: [],
      userId: "",
      postId: "",
      groupOptions: [],
      queryInParams: {},
      // 表单参数
      form: {},
      formView: {},
      termTimeShifList: [],
      tableCycleData: [],
      termScheduleList: [],
      cycleScheduleList: [],
      statusOptions: [
        { value: 0, label: "启用" },
        { value: 1, label: "停用" }
      ],
      rules: {
        scheduleDateRange: [
          { required: true, message: "排班时间不能为空", trigger: "blur" }
        ],
        dept: [{ required: true, message: "班组不能为空", trigger: "blur" }]
      },
      //班组信息
      deptInfo: [],
      //详情检索
      detailQuery: {}
    };
  },
  created() {
    this.getList();
    this.listDept();
  },
  methods: {
    //查询班组
    listDept() {
      tableRecords({ category: 2 }).then(response => {
        this.deptInfo = response.rows;
      });
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.statusArray = selection.map(item => item.status);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        dateTime: undefined,
        status: undefined,
        userName: undefined,
        postName: undefined
      };
      this.queryInParams = {
        id: undefined,
        userName: undefined,
        postName: undefined
      };
      this.scheduleDateRange = [];
      this.userId = "";
      this.postId = "";
      this.tableData = [];
      this.tableTitleData = [];
      this.resultData = "";
      this.resetForm("form");
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      listTermSchedule(this.queryParams).then(response => {
        this.termScheduleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    //点击查询事件
    handleViewTableQuery() {
      this.handleViewShow(this.detailQuery);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 重置详情按钮操作 */
    resetDetailQuery() {
      this.resetForm("formView");
      let query = this.detailQuery;
      this.detailQuery = {
        scheduleTaskId: query.scheduleTaskId
      };
    },
    handleShowDel(startTime) {
      return timeAfterNow(startTime);
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      const status = row.status || this.statusArray;
      if (id == "") {
        this.$alert("请先选中记录后再删除！", "错误提示", {
          dangerouslyUseHTMLString: true
        });
        return;
      }
      this.$confirm("是否删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delTermSchedule(id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let form = {
            deptId: this.form.dept.deptId,
            deptName: this.form.dept.deptName,
            scheduleStartTime: getCurrentMonthFirstDay(
              this.form.scheduleDateRange
            ),
            scheduleEndTime: getCurrentMonthLastDay(this.form.scheduleDateRange)
          };

          //校验
          shiftDateVerification(form).then(response => {
            if (response.code === 200 && response.data.length > 0) {
              this.$confirm(
                "系统中已存在该班组在此段日期的工作排班计划,是否确认导出该模板?",
                "警告",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                }
              ).then(() => {
                this.downloadTemplate(form);
              });
            } else {
              this.downloadTemplate(form);
            }
          });
        }
      });
    },

    //下载模板
    downloadTemplate: function(form) {
      this.open = false;
      window.location.href =
        process.env.VUE_APP_BASE_API +
        "/scheduling/plan/exportTemplate?deptId=" +
        encodeURI(form.deptId) +
        "&deptName=" +
        encodeURI(form.deptName) +
        "&scheduleStartTime=" +
        encodeURI(form.scheduleStartTime) +
        "&scheduleEndTime=" +
        encodeURI(form.scheduleEndTime);
    },

    //添加排班
    handleAdd() {
      this.open = true;
      this.title = "下载排班模板";
    },

    //展示详情对话框
    handleView(row) {
      //页面跳转
      this.$router.push({
        path: "/basic/termScheduleDetail",
        query: {
          scheduleTaskId: row.id,
          title:
            row.deptName +
            "-排班计划 " +
            row.scheduleStartTime +
            " - " +
            row.scheduleEndTime
        }
      });

      // this.openView = true;
      // this.title = '';
      // this.reset();
      // this.detailQuery = {
      //   scheduleTaskId:row.id,
      // };
      // this.handleViewShow(this.detailQuery);
    },

    //详情接口
    handleViewShow(query) {
      this.planDays = [];
      getTermSchedule(query).then(response => {
        console.log(response);
        let list = response.data;
        if (list.length > 0) {
          let days = list[0].planDays;
          for (let day of days) {
            this.planDays.push(day.scheduleDate);
          }
        }
        this.tableData = list;
        this.userloading = false;
      });
    },

    //ToDo Hush.
    handleExport() {
      const id = this.ids;

      if (id.length > 1) {
        this.$alert("抱歉，只能选择一条记录导出排班信息", "错误提示", {
          dangerouslyUseHTMLString: true
        });
        return;
      }

      if (id.length < 1) {
        this.$alert("抱歉，请选择一条记录导出排班信息", "错误提示", {
          dangerouslyUseHTMLString: true
        });
        return;
      }
      let url =
        process.env.VUE_APP_BASE_API +
        "/workJobApi/termSchedule/userScheduleExport?id=" +
        encodeURI(id);
      window.open(url);
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
    },
    beforeUpload(file, fileList) {
      this.fileList = fileList;
    },

    // 提交上传文件
    submitFileForm() {
      this.upload.isUploading = true;
      importSchedule(this.upload.url, this.fileList)
        .then(res => {
          this.upload.open = false;
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();

          res.code === 200 ? this.msgSuccess(res.msg) : this.msgError(res.msg);
          if (this.upload.flag === 1) {
            this.getList();
          } else {
            this.handleViewShow(this.detailQuery);
          }
        })
        .catch(() => {
          this.upload.isUploading = false;
        });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.flag = 1;
      this.upload.url = "/scheduling/plan/importTemplate";
      this.upload.title = "导入排班信息";
      this.upload.open = true;
    },

    /** 覆盖按钮操作 */
    handleImportToCover() {
      this.upload.flag = 2;
      this.upload.url =
        "/scheduling/plan/coverSchedulingPlanTemplate?id=" +
        this.detailQuery.scheduleTaskId;
      this.upload.title = "覆盖原排班信息";
      this.upload.open = true;
    },

    /** 上传取消 */
    uploadCancel() {
      this.upload.open = false;
      this.$refs.upload.clearFiles();
    }
  }
};
</script>

<style scoped></style>
